﻿using System.IO;
using System.Text;
using System.Windows.Controls;
using System.Xml;

namespace HandTest
{
    partial class MainWindow
    {
        readonly StringBuilder strBuilder = new StringBuilder();
        readonly XmlDocument xmlDoc = new XmlDocument();

        void SaveAsXml(string path)
        {
            strBuilder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            strBuilder.Append("<Root>");

            strBuilder.Append("<Tree Name=\"BaseComboTree\">");
            TreeToXml(baseComboTree);
            strBuilder.Append("</Tree>");

            strBuilder.Append("<Tree Name=\"RepeatExtraTree\">");
            TreeToXml(repeatableExtraTree);
            strBuilder.Append("</Tree>");

            strBuilder.Append("<Tree Name=\"UnrepeatExtraTree\">");
            TreeToXml(unrepeatableExtraTree);
            strBuilder.Append("</Tree>");

            strBuilder.Append("</Root>");
            File.WriteAllText(path, strBuilder.ToString(), System.Text.Encoding.UTF8);
            strBuilder.Clear();
            ClearComboTrees();
            testFileList.ItemsSource = testDirectory.GetFiles("*.test");
        }

        void LoadAsXml(FileInfo testFile)
        {
            xmlDoc.Load(testFile.FullName);
            var trees = xmlDoc.DocumentElement.ChildNodes;

            ClearComboTrees();

            XmlToTree(trees[0], baseComboTree);
            XmlToTree(trees[1], repeatableExtraTree);
            XmlToTree(trees[2], unrepeatableExtraTree);
        }

        void TreeToXml(ItemsControl tree)
        {
            foreach (TreeViewItem item in tree.Items)
            {
                strBuilder.Append(GetNodeText(item));
                if (item.Items.Count > 0)
                    TreeToXml(item);
                strBuilder.Append("</Node>");
            }

            string GetNodeText(TreeViewItem item) => "<Node Name=\"" + item.Header + "\">";
        }

        void XmlToTree(XmlNode node, ItemsControl tree)
        {
            foreach (XmlNode child in node.ChildNodes)
            {
                TreeViewItem item = new TreeViewItem() { Header = child.Attributes["Name"].Value, IsExpanded = true };
                tree.Items.Add(item);
                XmlToTree(child, item);
            }
        }

        void ClearComboTrees()
        {
            baseComboTree.Items.Clear();
            repeatableExtraTree.Items.Clear();
            unrepeatableExtraTree.Items.Clear();
        }
    }
}
